var categoryDetails;		// 存放该目录下所有书籍信息
var pageSize = 4;
var bookTemplate = document.getElementById("bookTemplate").innerHTML;
var bookListElement = document.getElementsByClassName("booklist")[0];
var pagerElement = document.getElementsByClassName("pager")[0];

function showCategoryDetails(categoryId) {
	var url = 'dataservice/category' +
		(categoryId ? categoryId : "") +
		'.js';
	getResource(url, function(result, data) {
		if(result){
			categoryDetails = JSON.parse(data);
		} else{
			categoryDetails = [];
		}
		generatePagerHtml();	// 生成分页标签
		showPagedBooks(1);		// 显示第一页的数据
	});
}

function generatePagerHtml(){
	var html = "";
	pageCount = categoryDetails.length / 4 + ((categoryDetails.length % 4) ? 1 : 0);
	for(var i=1;i<=pageCount;i++){
		html += "<span class='pageritem' onclick='showPagedBooks(" 
			+ i + ")'>" + i + "</span>";
	}
	pagerElement.innerHTML = html;
}

function showPagedBooks(pageIndex){
	// 筛选出在本页上显示的若干条数据
	var booksInPage = categoryDetails.slice(pageSize * (pageIndex-1), pageSize*pageIndex);
	generateBookListHtml(bookTemplate, booksInPage);
	
	// 设置当前页的分页元素属性为"active"
	for(var i=0;i<pagerElement.childNodes.length;i++){
		var pagerItem = pagerElement.childNodes[i];
		if(pageIndex == (i+1)){
			pagerItem.classList.add("active");
		}else{
			pagerItem.classList.remove("active");
		}
	}
}

function generateBookListHtml(template, books) {
	var result = "";
	for (var i = 0; i < books.length; i++) {
		var temp = template;
		var index1 = temp.indexOf("{{");
		var index2;
		var word;
		while (index1 >= 0) {
			index2 = temp.indexOf("}}", index1);
			word = temp.substring(index1 + 2, index2);
			switch (word) {
				case 'id':
					temp = temp.replace("{{id}}", books[i].id);
					break;
				case 'title':
					temp = temp.replace("{{title}}", books[i].title);
					break;
				case 'pictureurl':
					var url = books[i].pictureurl ? books[i].pictureurl : "nopicture.png";
					temp = temp.replace("{{pictureurl}}", url);
					break;
				case 'publisher':
					temp = temp.replace("{{publisher}}", books[i].publisher);
					break;
				case 'publishdate':
					temp = temp.replace("{{publishdate}}", books[i].publisherdate);
					break;
				case 'listprice':
					temp = temp.replace("{{listprice}}", books[i].listprice);
					break;
				case 'reducedprice':
					temp = temp.replace("{{reducedprice}}", books[i].reducedprice);
					break;
				case 'authors':
					var authorStr = "";
					for (var j = 0; j < books[i].authors.length; j++) {
						var author = books[i].authors[j];
						if (author.country) {
							authorStr += "(" + author.country + ")";
						}
						authorStr += author.name + "&nbsp;&nbsp;"
					}
					temp = temp.replace("{{authors}}", authorStr);
					break;
			}
			index1 = temp.indexOf("{{", index1 + 2);
		}
		result += temp;
	}
	bookListElement.innerHTML = result;
}